import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import {Layout, Button, Col, Form, Input, Row, Table, ConfigProvider, Modal, Tree, Checkbox} from "antd/lib";
import zhCN from 'antd/es/locale/zh_CN';
import Tabletype from "@/services/tabletype";
import {createBrowserHistory} from 'history'
import notification from "@/services/notification";
import {get} from "lodash";
import Enums from "@/services/enums";
import routes from "@/services/routes";
import "./layoutheight.less";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined} from "@ant-design/icons";
const customHistory = createBrowserHistory();
const { Sider } = Layout;
const { confirm } = Modal;
class TabletypeList extends React.Component {
  state = {
    page: 1,
    pagesize: 10,
    total:10,
    loading: false,
    name: '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      name: this.state.name,
      bill_enum: this.state.selectedKeys,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
     Tabletype.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
  };
  handlesel = () => {
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      name: this.state.name,
      bill_enum: this.state.selectedKeys,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let param={
      page: pagination.current,
      pagesize: pagination.pageSize,
      name: this.state.name,
      bill_enum: this.state.selectedKeys,
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if(record.status !==0)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除单据?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Tabletype.delete(record).then(()=>{
          notification.success("单据删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            name: this.state.name,
            bill_enum: this.state.selectedKeys,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    Enums.items("bill_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
  }
  onSelect = (selectedKeys, e) => {
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            name: this.state.name,
            bill_enum: selectedKeys[0],
          }
          this.fetch(param);
    // this.setState({
    //   selectedKeys: selectedKeys[0],
    //   selectedTitle: e.node.props.title,
    // });
};
onDragEnter = info => {
    console.log(info);
  };
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
        const listcolumns = [
      {
        title: '单据名称',
        key: 'name',
        dataIndex: 'name',
        render: (text, record) => (
          <Router  history={customHistory}>
            <Link to={`/tabletype/new/${record.id}`}>{text}</Link>
           </Router>
        ),
      },
      {
        title: '自动编号',
        dataIndex: 'numauto',
        key: 'numauto',
        render: (text, record) => (
          <span>
            <Checkbox checked={text}></Checkbox>
          </span>
        ),
      },
      {
        title: '手动编号',
        dataIndex: 'numhand',
        key: 'numhand',
        render: (text, record) => (
          <span>
            <Checkbox checked={text}></Checkbox>
          </span>
        ),
      },
      {
        title: '标志',
        dataIndex: 'numhead',
        key: 'numhead',
      },
      {
        title: '日期',
        dataIndex: 'numdate',
        key: 'numdate',
      },
      {
        title: '流水号',
        dataIndex: 'numfoot',
        key: 'numfoot',
      },
      {
        title: '流水号长度',
        dataIndex: 'footlenth',
        key: 'footlenth',
      },
    ];
    return (
  <ConfigProvider locale={zhCN}>
    {/*<div className="page-dashboard-list">*/}
      <div className="container">
        <PageHeader title="单据列表"/>
      </div>
      <Layout className="ant-layout">
          <Layout className="ant-layout">
            <Sider width={300} style={{ background: '#fff' }}>
              <Tree
                className="draggable-tree"
                draggable
                blockNode
                showIcon
                // showLine
                switcherIcon={<DownOutlined />}
                defaultExpandAll
                onDragEnter={this.onDragEnter}
                onSelect={this.onSelect}
                treeData={this.state.gData}
              />
            </Sider>
        <Layout className="ant-layout" style={{ padding: '0 24px 24px' }}>
         <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
          <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="单据名称">
              <Input
                value={this.state.name}
                onChange={e => this.setState({name:e.target.value})}
                placeholder="单据名称"
              />
						</Form.Item>
				  </Col>
          </Row>
          <Row>
				  {/*<Col span={10}>*/}
          {/*   <Router  history={customHistory}>*/}
          {/*    <Link to={`/tabletype/new/0`}>新增</Link>*/}
          {/*   </Router>*/}
				  {/*</Col>*/}
				  <Col span={10}>
          <Button type="primary" onClick={() => this.handlesel()} >
            <i className="fa fa-search m-r-5" />
            查询
          </Button>
				  </Col>
          </Row>
         </Form>
          <div>
              <Table rowKey='id'
                     columns={listcolumns}
                     dataSource={this.state.data}
                     pagination={paginationProps}
                     loading={this.state.loading}
                     onChange={this.handleTableChange}
              />
         </div>
        </Layout>
        </Layout>
       </Layout>
    {/*</div>*/}
  </ConfigProvider>
    );
  }
}

// const TabletypeListPage = itemsList(
//   TabletypeList,
//   // () =>
//   //   new ResourceItemsSource({
//   //     getResource({ params: { currentPage } }) {
//   //       return {
//   //         all: Dashboard.query.bind(Dashboard),
//   //         favorites: Dashboard.favorites.bind(Dashboard),
//   //       }[currentPage];
//   //     },
//   //     getItemProcessor() {
//   //       return item => new Dashboard(item);
//   //     },
//   //   }),
//   // () => new UrlStateStorage({ orderByField: "created_at", orderByReverse: true })
// );

routes.register(
  "Tabletype.List",
  routeWithUserSession({
    path: "/tabletype",
    title: "单据号设置",
    render: pageProps => <TabletypeList {...pageProps} currentPage="tabletype" />,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/tabletype",
//     title: "我提交的单据类型",
//     render: pageProps => <TabletypeList {...pageProps} />,
//   }),
// ];
